package com.sensen.redis;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
import com.sensen.common.NoSqlClient;
import com.sensen.exception.RedisException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import redis.clients.jedis.JedisCluster;



/**
 * Created by Administrator on 2017/10/3.
 */
public class JedisClusterClient<T> implements NoSqlClient<T> {
    @Autowired
    private JedisCluster jedisCluster;
    public void set(String key, T value){
        //logger.info("-------------"+jedisCluster);
        jedisCluster.set(key,JSON.toJSONString(value,true));
    }

    @Override
    public void set(String key, T value, Long expiry) {

    }

    @Override
    public <T1> boolean exist(Class<T1> clazz, String key) {
        checkRedisKey(key);
        return jedisCluster.exists(key);
    }

    @Override
    public T get(String key, Class<T> clazz) {
        checkRedisKey(key);
        String value = jedisCluster.get(key);
        return JSON.parseObject(value, clazz);
    }

    @Override
    public <T1> void delete(String key) {
        checkRedisKey(key);
        jedisCluster.del(key);
    }

    @Override
    public <T1> void hashSet(String key, String hashKey, T1 hashValue) {
        checkRedisKey(key);
        jedisCluster.hset(key, hashKey, JSON.toJSONString(hashValue));
    }

    @Override
    public Object hashGet(String key, String hashKey, Class<?> hashValueClazz) {
        return null;
    }
    /**
     * 检查Redis参数
     *
     * @param key
     * @param value
     * @return
     */
    private String checkRedisNoSqlSupport(final String key, final T value) {
        checkRedisKey(key);
        if (value == null)
            throw new RedisException("value is null!");
        String stringValue = null;
        try {
            stringValue = JSON.toJSONString(value,true);
        } catch (JSONException e) {
            throw new RedisException("value toJSONString exception!");
        }
        if (StringUtils.isEmpty(stringValue))
            throw new RedisException("value is null!");
        return stringValue;
    }

    /**
     * 检查Redis key,redis key 长度建议不要超过1M,redis支持512M
     * @param key
     */
    private void checkRedisKey(final String key) {
        if (StringUtils.isEmpty(key))
            throw new RedisException("key is null!");
        if (key.length() > 1000000L)
            throw new RedisException("length of key greater than 1M!");
    }
}
